#pragma semicolon 1
#pragma newdecls required

#include <sourcemod>
#include <left4dhooks>
#include <geoip>
#include <dbi>

#define PLUGIN_VERSION "1.0"

Database g_dbRegions;

public Plugin myinfo =
{
	name = "l4d2_geoip_display",
	author = "豆瓣酱な",
	description = "显示玩家所在国家/省份/城市,带中文翻译.",
	version = PLUGIN_VERSION,
	url = "https://gitee.com/sweet-and-sour-bombs/adfvsdsd"
};

public void OnPluginStart()
{
	InitDatabase();
	HookEvent("player_activate", Event_PlayerActivate);

}

void InitDatabase()
{
	char error[512];
	g_dbRegions = SQLite_UseDatabase("l4d2_geoip_display", error, sizeof(error));
    
	if(g_dbRegions == null)
	{
		SetFailState("数据库初始化失败: %s", error);
		return;
	}

	// 创建三表结构
	SQL_FastQuery(g_dbRegions, "CREATE TABLE IF NOT EXISTS countries (country_id INTEGER PRIMARY KEY, pinyin TEXT, name_zh TEXT)");
	SQL_FastQuery(g_dbRegions, "CREATE TABLE IF NOT EXISTS provinces (province_id INTEGER PRIMARY KEY, country_id INTEGER, pinyin TEXT, name_zh TEXT, FOREIGN KEY(country_id) REFERENCES countries(country_id))");
	SQL_FastQuery(g_dbRegions, "CREATE TABLE IF NOT EXISTS cities (city_id INTEGER PRIMARY KEY, province_id INTEGER, pinyin TEXT, name_zh TEXT, FOREIGN KEY(province_id) REFERENCES provinces(province_id))");
}

public void Event_PlayerActivate(Event event, const char[] name, bool dontBroadcast)
{
	int userid = event.GetInt("userid");
	CreateTimer(0.1, Timer_DelayedWelcome, userid);
}


public Action Timer_DelayedWelcome(Handle timer, any userid)
{
	int client = GetClientOfUserId(userid);
	if(!IsValidClient(client)) return Plugin_Stop;
    
	char ip[32], country[64], region[64], city[64];
	GetClientIP(client, ip, sizeof(ip));
    
	// 获取地理信息
	GeoipCountry(ip, country, sizeof(country));
	GeoipRegion(ip, region, sizeof(region));
	GeoipCity(ip, city, sizeof(city));
    
	// 转换为拼音格式
	ConvertToPinyin(country, sizeof(country));
	ConvertToPinyin(region, sizeof(region));
	ConvertToPinyin(city, sizeof(city));
    

	QueryLocation(client, country, region, city);
	return Plugin_Stop;
}

void QueryLocation(int client, const char[] country, const char[] region, const char[] city)
{
	char error[512];
	char safeCountry[64], safeRegion[64], safeCity[64];
    
	// 防SQL注入处理
	SQL_EscapeString(g_dbRegions, country, safeCountry, sizeof(safeCountry));
	SQL_EscapeString(g_dbRegions, region, safeRegion, sizeof(safeRegion));
	SQL_EscapeString(g_dbRegions, city, safeCity, sizeof(safeCity));
    
	// 构建查询
	char query[512];
	Format(query, sizeof(query), 
	"SELECT c.name_zh, p.name_zh, ci.name_zh FROM countries c LEFT JOIN provinces p ON p.country_id = c.country_id AND p.pinyin = '%s' LEFT JOIN cities ci ON ci.province_id = p.province_id AND ci.pinyin = '%s' WHERE c.pinyin = '%s'",
	safeRegion, safeCity, safeCountry
	);
    
	// 执行查询
	DBResultSet results = SQL_Query(g_dbRegions, query);
	if(results == null)
	{
		SQL_GetError(g_dbRegions, error, sizeof(error));
		LogError("查询失败: %s", error);
		return;
	}
    
	// 处理结果
	if(results.FetchRow())
	{
		char countryCN[64], regionCN[64], cityCN[64];
		results.FetchString(0, countryCN, sizeof(countryCN));
		results.FetchString(1, regionCN, sizeof(regionCN));
		results.FetchString(2, cityCN, sizeof(cityCN));
        
		// 显示给玩家
		PrintToChatAll("\x04[提示] \x03%N \x04加入了游戏,来自 \x03%s %s %s", client, countryCN, regionCN, cityCN);
	}
	else
	{
		PrintToChatAll("\x04[提示] \x03%N \x04加入了游戏.", client);
	}
    
	delete results;
}

void ConvertToPinyin(char[] text, int maxlen)
{
    
	if(StrEqual(text, "China", false)) strcopy(text, maxlen, "zhongguo");
	else if(StrEqual(text, "Guangdong", false)) strcopy(text, maxlen, "guangdong");
	else if(StrEqual(text, "Shenzhen", false)) strcopy(text, maxlen, "shenzhen");
}

bool IsValidClient(int client)
{
	return (client > 0 && client <= MaxClients && IsClientInGame(client) && !IsFakeClient(client));
}

public void OnPluginEnd()
{
	if(g_dbRegions != null) delete g_dbRegions;
}